package me.xlgp.xiquzimu.ui.changci;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import me.xlgp.xiquzimu.data.ChangDuanInfoRepository;
import me.xlgp.xiquzimu.data.ChangDuanRepository;
import me.xlgp.xiquzimu.data.JuZhongRepository;
import me.xlgp.xiquzimu.model.ChangCi;
import me.xlgp.xiquzimu.model.ChangDuan;
import me.xlgp.xiquzimu.model.ChangDuanInfo;
import me.xlgp.xiquzimu.model.JuZhong;
import me.xlgp.xiquzimu.util.ChangDuanHelper;

public class ChangCiEditViewModel extends AndroidViewModel {

    public MutableLiveData<String> state = new MutableLiveData<>();
    public MutableLiveData<Boolean> saving = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> saved = new MutableLiveData<>(false);
    public MutableLiveData<List<String>> juZhongList = new MutableLiveData<>();
    public MediatorLiveData<Integer> selectedItemPosition = new MediatorLiveData<>();
    private MutableLiveData<ChangDuanInfo> changDuanInfoLiveData;

    public ChangCiEditViewModel(@NonNull @NotNull Application application) {
        super(application);
        loadJuZhongList();
    }

    public MutableLiveData<ChangDuanInfo> getChangDuanInfo() {
        if (changDuanInfoLiveData == null) {
            changDuanInfoLiveData = new MutableLiveData<>();
            changDuanInfoLiveData.postValue(new ChangDuanInfo());
            selectedItemPosition.addSource(changDuanInfoLiveData, changDuanInfo -> setSpinner());
        }
        return changDuanInfoLiveData;
    }

    public void addChangCiItem() {
        Objects.requireNonNull(getChangDuanInfo().getValue()).getChangCiList().add(new ChangCi());
    }

    public void loadJuZhongList() {
        new JuZhongRepository().list().subscribe(new Observer<List<JuZhong>>() {
            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.rxjava3.annotations.NonNull List<JuZhong> juZhongs) {
                juZhongList.postValue(juZhongs.stream().map(JuZhong::getName).collect(Collectors.toList()));
            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void setSpinner() {
        if (changDuanInfoLiveData.getValue() == null) {
            return;
        }
        ChangDuan changDuan = changDuanInfoLiveData.getValue().getChangDuan();
        if (changDuan == null) return;
        if (juZhongList.getValue() == null) return;
        String juZhong = changDuan.getJuZhong();

        for (int i = 0; i < juZhongList.getValue().size(); i++) {
            if (juZhongList.getValue().get(i).equals(juZhong)) {
                selectedItemPosition.setValue(i);
                break;
            }
        }
    }

    public void loadData(int id) {
        if (id < 0) {
            state.postValue("唱段ID : " + id + " 不正确");
            return;
        }
        new ChangDuanInfoRepository().getChangDuanInfo(id).subscribe(new Observer<ChangDuanInfo>() {
            private Disposable disposable;

            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(@io.reactivex.rxjava3.annotations.NonNull ChangDuanInfo ziMuInfo) {
                changDuanInfoLiveData.postValue(ziMuInfo);
            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                state.postValue("获取唱段失败；" + e.getMessage());
                if (disposable != null && !disposable.isDisposed()) {
                    disposable.isDisposed();
                }
            }

            @Override
            public void onComplete() {
                if (disposable != null && !disposable.isDisposed()) {
                    disposable.isDisposed();
                }
            }
        });
    }

    public void save() {
        ChangDuanInfo changDuanInfo = changDuanInfoLiveData.getValue();
        if (changDuanInfo == null) {
            state.postValue("无数据可保存");
            return;
        }
        try {
            //先对处理数据
            ChangDuanHelper.parseChangCiListByDelayMillis(changDuanInfo);
        } catch (Exception e) {
            Log.e("TAG", "save: ", e);
            state.setValue("数据格式不正确");
            return;
        }
        state.postValue("正在保存...");
        saving.postValue(true);

        List<ChangCi> changCiList = changDuanInfo.getChangCiList();
        for (int i = 0, len = changCiList.size(); i < len; i++) {//需要对其重新排序，因为唱词可能会调整顺序
            changCiList.get(i).setOrderId(i + 1);
        }
        if (changDuanInfo.getChangDuan().getId() == null) {//新增
            new ChangDuanRepository().saveAynsc(changDuanInfo).subscribe(getSaveObserver());
        } else {//更新
            for (int i = 0, len = changCiList.size(); i < len; i++) {
                changCiList.get(i).setChangDuanId(changDuanInfo.getChangDuan().getId());
            }
            new ChangDuanInfoRepository().save(changDuanInfo).subscribe(getSaveObserver());
        }
    }

    private Observer<Object> getSaveObserver() {
        return new Observer<Object>() {
            private Disposable disposable;

            @Override
            public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(@io.reactivex.rxjava3.annotations.NonNull Object o) {
                state.postValue("保存成功");
                finish();
            }

            @Override
            public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                state.postValue("保存失败；" + e.getMessage());
                finish();
            }

            private void finish() {
                if (disposable != null && !disposable.isDisposed()) {
                    disposable.isDisposed();
                }
                saving.postValue(false);
                saved.postValue(true);
            }

            @Override
            public void onComplete() {
                state.postValue("保存成功");
                finish();
            }
        };
    }

    public void updateJuZhong(Integer position) {
        if (changDuanInfoLiveData.getValue() == null) {
            return;
        }
        if (juZhongList.getValue() == null) {
            return;
        }
        changDuanInfoLiveData.getValue().getChangDuan().setJuZhong(juZhongList.getValue().get(position));
    }
}
